<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书修改</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/art-template/4.13.2/lib/template-web.js"></script>
</head>

<body>
    <h2>修改图书</h2>

    <div id="form"></div>

    <button id="btn">提交</button>

    <script id="form-content" type="text/html">
    <input type="hidden" name="_id" value="<%=book._id%>" id="_id">
    书名: <input type="text" name="name" value="<%=book.name%>" id="name"><br/>
    作者: <input type="text" name="author" value="<%=book.author%>" id="author"><br/>
    价格: <input type="number" name="price" value="<%=book.price%>" id="price"><br/>
  </script>

    <script>
        /* 
        读取query参数指定参数名的值
        */
        function getQueryValue(name) {
            var str = location.href.split('?');
            var query = str[1];
            var vars = query.split('&');
            for (var i = 0; i < vars.length; i++) {
                var pair = vars[i].split("=");
                if (pair[0] == name) {
                    return pair[1];
                }
            }
            return (false);
        }

        // 获取query参数
        /* 
        根据参数请求获取图书信息显示
        */
        async function getBook() {
            const id = getQueryValue('id')
            // const response = await axios({
            //     url: `http://localhost:9999/book/${id}`,
            //     method: 'get',
            // })
            const response = await axios.get(`http://localhost:9999/book/${id}`)
            const book = response.data.data
            const html = template('form-content', { book })
            document.querySelector('#form').innerHTML = html
        }
        getBook()
        // 根据获得的参数渲染页面
        document.querySelector('#btn').onclick = async () => {
            const _id = document.getElementById('_id').value
            const name = document.getElementById('name').value
            const author = document.getElementById('author').value
            const price = document.getElementById('price').value
            // 将获取的页面数据发axios请求到路由
            // await axios({
            //     url: 'http://localhost:9999/book',
            //     method: 'put',
            //     data: {_id, name, author, price}
            // })
            await axios.put('http://localhost:9999/book', {_id, name, author, price})
            window.location = '/cient/books.html'
        }


    </script>
</body>

</html>